【Golang零基础入门】05 接口

什么是接口

  • 接口是行为方法的抽象与概括
  • 接口只有方法声明,不用和实现的细节绑定在一起,也没有数据字段
  • 接口是隐式实现的,只要某个类型拥有该接口的所有方法,就算是接口实现,无需像其他语言里的implements显示声明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type action interface {
run()
}

type cat struct {
name string
}

func (c cat)run() {
fmt.Println("Run " + c.name)
}

type dog struct {
name string
}

func (d dog)run(){
fmt.Println("Run " + d.name)
}

嵌入接口

我们上次说结构体的时候,已经说过结构体是能够嵌入的,接口也是可以嵌入的,例如
animal嵌入了action、display接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type animal interface {
action
display
}

type action interface {
run()
}

type display interface {
color() string
}

type cat struct {
name string
}

func (c cat)run() {
fmt.Println("Run " + c.name)
}

func (c cat)color() string {
return "Grey"
}

类型断言

断言类型的语法:x.(T),这里x表示一个接口的类型,T表示一个类型(也可为接口类型)。
一个类型断言检查一个接口对象x的动态类型是否和断言的类型T匹配。

如果类型比较少的话,可以用if ok pattern

1
2
3
4
5
6
7
func assertCat(a animal)  {
if catA, ok := a.(cat); ok {
fmt.Println("Animal : " + catA.name)
return
}
fmt.Println("Unknow")
}

如果类型较多的情况可以使用switch case

1
2
3
4
5
6
7
8
func assertAnimal(a animal)  {
switch v := a.(type) {
case cat:
fmt.Println("Animal: " + v.name)
default:
fmt.Println("Unknown animal")
}
}

多态

我们在实现多态的时候,可以直接做一层封装,接受接口的实例,这样便实现了类似抽象工厂模式

1
2
3
4
5
6
7
8
9
10
func animalRun(a animal)  {
a.run()
}

func main() {
catA := cat{"cat"}
dogA := dog{"dog"}
animalRun(catA)
animalRun(dogA)
}
您的支持将鼓励我继续创作!